from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from django.conf import settings
from dictapi.models import *
from dictapi.serializers import *
import requests
import logging

logger = logging.getLogger(__name__)


class SaveWordEntries(APIView):
    name = 'save_word_entries'

    def post(self, request):
        res = ResBody()
        res.update(data=timezone.now())
        return Response(data=res.data)


class SearchAutoComplete(ListAPIView):
    name = 'auto'
    serializer_class = AutoCompleteSerializer

    def get_queryset(self):
        key = self.request.query_params.get('key', '')
        if len(key) > 0:
            return WordList.objects.filter(word__startswith=key).order_by('word')[:10]
        else:
            return None


class LookupWord(APIView):
    name = 'lookup'
    serializer_class = WordEntrySerializer

    def get(self, request, word):
        entry = None
        if len(word) > 0:
            try:
                entry = WordEntry.objects.filter(entry__word='love')
            except Exception as e:
                # logger.debug(str(e))
                pass
        if not entry:
            headers = {'app_id': settings.app_id, 'app_key': settings.app_key}
            res = requests.get(url=settings.uri.format(word), headers=headers)
            if res.status == 200:
                entry = WordEntry.objects.create(entry=res.json['results'], meta=res.json()['metadata'])
                headers = {'app_id': settings.APP_ID, 'app_key': settings.APP_KEY}
                res = requests.get(url=settings.URI.format(word), headers=headers)
                if res.status_code == 200:
                    entry = WordEntry.objects.create(entry=res.json()['results'], meta=res.json()['metadata'])
        return Response(data=WordEntrySerializer(entry).data)
